import axios from 'axios';
import router from '@/router';

// 定义基础URL常量
const BASE_URL = 'http://localhost:8080';
const API_URL = `${BASE_URL}/api`;

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 添加时间戳用于计算请求耗时
    config.timestamp = new Date().getTime();
    
    // 打印请求信息
    console.group(`%c请求: ${config.method.toUpperCase()} ${config.url}`, 'color: #2563eb; font-weight: bold;');
    console.log('请求URL:', `${config.baseURL}${config.url}`);
    console.log('请求方法:', config.method.toUpperCase());
    
    // 打印请求头
    console.log('请求头:', {...config.headers});
    
    // 打印请求参数
    if (config.params) {
      console.log('URL参数:', config.params);
      console.log('参数类型:', Object.entries(config.params).reduce((acc, [key, value]) => {
        acc[key] = typeof value;
        return acc;
      }, {}));
    }
    
    // 打印请求体
    if (config.data) {
      if (config.data instanceof FormData) {
        const formDataEntries = {};
        for (let pair of config.data.entries()) {
          formDataEntries[pair[0]] = pair[1] instanceof Blob ? `[Blob ${pair[1].size} bytes]` : pair[1];
        }
        console.log('请求体 (FormData):', formDataEntries);
      } else {
        console.log('请求体:', config.data);
        console.log('请求体类型:', Object.entries(config.data).reduce((acc, [key, value]) => {
          acc[key] = typeof value;
          return acc;
        }, {}));
      }
    }
    console.groupEnd();
    
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    
    // 如果有token则添加到请求头
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 如果是上传文件的请求，修改Content-Type
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }
    
    return config;
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    // 打印响应信息
    console.group(`%c响应: ${response.config.method.toUpperCase()} ${response.config.url}`, 'color: #16a34a; font-weight: bold;');
    console.log('响应状态:', response.status, response.statusText);
    console.log('响应头:', response.headers);
    
    // 打印响应数据
    console.log('响应数据:', response.data);
    if (response.data && typeof response.data === 'object') {
      console.log('响应数据类型:', Object.entries(response.data).reduce((acc, [key, value]) => {
        acc[key] = Array.isArray(value) ? `Array[${value.length}]` : typeof value;
        return acc;
      }, {}));
    }
    
    // 计算请求耗时
    const requestTime = new Date().getTime() - response.config.timestamp;
    console.log('请求耗时:', `${requestTime}ms`);
    console.groupEnd();
    
    // 如果服务器返回的是二进制数据，直接返回
    if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
      return response;
    }
    
    const res = response.data;
    
    // 这里假设后端返回的格式为 { code, message, data }
    if (res.code !== undefined) {
      // 成功状态
      if (res.code === 200 || res.code === 0) {
        // 特殊处理登录响应
        if (response.config.url === '/user/login') {
          // 存储token和用户角色
          if (res.data && res.data.token) {
            // 打印登录响应数据，用于调试
            console.log('登录响应数据:', res.data);
            
            // 解析JWT token获取用户信息
            const tokenParts = res.data.token.split('.');
            if (tokenParts.length === 3) {
              try {
                const tokenPayload = JSON.parse(atob(tokenParts[1]));
            console.log('Token payload:', tokenPayload);
            
                // 确保保存完整的 token 值
            localStorage.setItem('token', res.data.token);
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('userRole', res.data.role || 'user');
                
                // 保存用户ID - 优先使用响应中的userId
                let userId = null;
                if (res.data.id) {
                  userId = res.data.id;
                  console.log('从响应data.id获取到用户ID:', userId);
                } else if (res.data.userId) {
                  userId = res.data.userId;
                  console.log('从响应data.userId获取到用户ID:', userId);
                } else if (tokenPayload.userId) {
                  userId = tokenPayload.userId;
                  console.log('从JWT.userId获取到用户ID:', userId);
                } else if (tokenPayload.id) {
                  userId = tokenPayload.id;
                  console.log('从JWT.id获取到用户ID:', userId);
                } else if (tokenPayload.user_id) {
                  userId = tokenPayload.user_id;
                  console.log('从JWT.user_id获取到用户ID:', userId);
                } else if (tokenPayload.sub) {
                  userId = tokenPayload.sub;
                  console.log('从JWT.sub获取到用户ID:', userId);
                }
                
                if (userId) {
                  // 同时保存到独立的userId和user对象中
                  localStorage.setItem('userId', userId);
                  
                  // 保存完整用户对象
                  const userData = {
                    id: userId,
                    username: tokenPayload.username || res.data.username || '',
                    role: res.data.role || tokenPayload.role || 'user'
                  };
                  
                  localStorage.setItem('user', JSON.stringify(userData));
                  console.log('保存到localStorage的user对象:', userData);
                } else {
                  console.warn('未能从任何来源获取到用户ID');
                }
              } catch (e) {
                console.error('解析JWT失败:', e);
              }
            }
          }
          return res.data;  // 返回完整的data对象，包含role和token
        }
        return res.data;
      }
      
      // 特定的错误码处理
      if (res.code === 401) {
        // 未登录或token过期，清除所有登录信息
        clearAuthInfo();
        router.push('/login');
        throw new Error(res.message || '未登录或登录已过期');
      }
      
      // 其他业务错误
      throw new Error(res.message || '请求失败');
    }
    
    // 后端没有按照约定格式返回数据，直接返回响应数据
    return res;
  },
  error => {
    // 打印错误信息
    if (error.response) {
      console.group(`%c响应错误: ${error.config?.method?.toUpperCase() || 'UNKNOWN'} ${error.config?.url || 'UNKNOWN'}`, 'color: #dc2626; font-weight: bold;');
      console.log('错误状态:', error.response.status, error.response.statusText);
      console.log('响应头:', error.response.headers);
      console.log('响应数据:', error.response.data);
      console.groupEnd();
    } else if (error.request) {
      console.group(`%c请求错误: ${error.config?.method?.toUpperCase() || 'UNKNOWN'} ${error.config?.url || 'UNKNOWN'}`, 'color: #dc2626; font-weight: bold;');
      console.log('未收到响应:', error.request);
      console.groupEnd();
    } else {
      console.group('%c请求配置错误', 'color: #dc2626; font-weight: bold;');
      console.log('错误信息:', error.message);
      console.log('配置信息:', error.config || '无配置信息');
      console.groupEnd();
    }
    
    // 响应错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      const { status } = error.response;
      
      switch (status) {
        case 400:
          error.message = '请求错误';
          break;
        case 401:
          // 未授权或token过期，清除所有登录信息
          clearAuthInfo();
          // 避免在登录页面再次跳转到登录页面
          if (router.currentRoute.value.path !== '/login') {
            router.push('/login');
          }
          error.message = '未登录或登录已过期';
          break;
        case 403:
          error.message = '拒绝访问';
          break;
        case 404:
          error.message = '请求的资源不存在';
          break;
        case 500:
          error.message = '服务器内部错误';
          break;
        default:
          error.message = `未知错误(${status})`;
      }
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      error.message = '服务器无响应';
    } else {
      // 请求配置出错
      error.message = '请求配置错误';
    }
    
    // 网络错误
    if (error.message.includes('Network Error')) {
      error.message = '网络连接错误';
    }
    
    // 超时错误
    if (error.message.includes('timeout')) {
      error.message = '请求超时';
    }
    
    console.error('响应错误:', error.message);
    return Promise.reject(error);
  }
);

// 清除所有登录相关信息的函数
const clearAuthInfo = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('isLoggedIn');
  localStorage.removeItem('userRole');
  localStorage.removeItem('userId');
  localStorage.removeItem('username');
  localStorage.removeItem('cachedAvatarUrl');
  localStorage.removeItem('avatarCacheTime');
  console.log('已清除登录信息');
}

// 常用请求方法封装
const http = {
  get: (url, params) => apiClient.get(url, { params }),
  post: (url, data) => apiClient.post(url, data),
  put: (url, data) => apiClient.put(url, data),
  delete: (url) => apiClient.delete(url),
  upload: (url, file) => {
    const formData = new FormData();
    formData.append('file', file);
    return apiClient.post(url, formData);
  },
  download: (url, params) => {
    return apiClient.get(url, { 
      params, 
      responseType: 'blob' 
    });
  }
};

// API接口定义
const api = {
  // 辅助函数 - 构建封面URL
  getCoverUrl: (input) => {
    try {
      // 如果是直接的ID，使用API路径获取封面数据
      if (typeof input === 'number' || (typeof input === 'string' && !isNaN(input))) {
        return `${API_URL}/user/book/cover/${input}`;
      }
      
      // 如果是书籍对象
      if (input && typeof input === 'object') {
        // 如果对象的cover属性已经是完整URL，直接返回
        if (input.cover && typeof input.cover === 'string' && 
            (input.cover.startsWith('http://') || input.cover.startsWith('https://'))) {
          return input.cover;
        }
        
        // 否则使用ID请求封面API
        if (input.id) {
          return `${API_URL}/user/book/cover/${input.id}`;
        }
      }
      
      // 默认返回空字符串
      return '';
    } catch (error) {
      console.error('获取封面URL出错:', error);
      return '';
    }
  },
  
  // 用户相关接口
  user: {
    // 认证相关
    login: (data) => http.post('/user/login', data),
    register: (data) => http.post('/user/register', {
      username: data.username,
      password: data.password,
      real_name: data.real_name,
      student_id: data.student_id,
      department: data.department,
      email: data.email,
      phone: data.phone,
      wechat: data.wechat
    }),
    logout: () => {
      clearAuthInfo();
      return Promise.resolve();
    },
    
    // 用户信息相关
    getInfo: () => http.get('/user/info'),
    getProfile: () => http.get('/profile'),
    updateInfo: (data) => http.put('/profile', data),
    uploadAvatar: (file) => {
      const formData = new FormData();
      formData.append('file', file);
      return apiClient.post('/profile/uploadAvatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    },
    downloadAvatar: () => {
      return apiClient.get('/profile/downloadAvatar');
    },
    modifyPassword: (data) => http.post('/profile/modifyPassword', data),
    
    // 用户设置相关
    getSettings: () => http.get('/user/settings'),
    updateSettings: (data) => {
      // 确保移除notification_system字段，避免后端数据库错误
      const { notification_system, ...safeData } = data;
      console.log('更新用户设置, 已移除system字段:', safeData);
      return http.post('/user/settings', safeData);
    },
    
    // 余额充值
    rechargeBalance: (amount) => apiClient.put(`/orders/recharge/${amount}`)
  },
  
  // 订单相关接口
  orders: {
    // 生成订单
    generate: (data) => apiClient.post('/orders/generate', data),
    // 获取所有订单
    getAll: (params) => apiClient.get('/orders', { params }),
    // 获取订单详情
    getDetail: (orderId) => apiClient.get('/orders/orderDetail', { 
      params: { order_id: orderId } 
    }),
    // 取消订单
    cancel: (orderId) => apiClient.put(`/orders/orderCancel/${orderId}`),
    // 支付订单
    pay: (data) => apiClient.patch('/orders/orderPay', data)
  },
  
  // 图书相关接口
  book: {
    // 图书列表和详情
    getList: (params) => apiClient.get('/user/book', { params }),
    search: (keyword, params = {}) => {
      return apiClient.get('/user/book/search', { 
        params: { 
          keyword,
          ...params 
        } 
      });
    },
    getDetail: (bookId) => apiClient.get(`/user/book/${bookId}`),
    recommend: (bookId) => apiClient.get('/user/book/recommend', { 
      params: { book_id: bookId } 
    }),
    getCover: (bookId) => apiClient.get(`/user/book/cover/${bookId}`),
    downloadCover: (bookId) => {
      return apiClient.get(`/user/book/cover/${bookId}`, {
        responseType: 'blob'
      });
    },
    addViews: (bookId) => apiClient.put(`/user/book/addViews/${bookId}`),
    toggleFavorite: (bookId) => apiClient.post('/user/book/favorites', { book_id: bookId }),
    
    // 获取已购买的书籍
    getLookBought: () => apiClient.get('/user/book/lookBought'),
    
    // 获取书籍分类
    getCategories: () => apiClient.get('/user/book/categories'),
    
    // 发布书籍
    publish: (bookData) => apiClient.post('/user/book/upload', bookData),
    
    // 编辑书籍信息
    editBook: (bookData) => apiClient.post('/user/book/editBook', bookData),
    
    // 获取我的书籍
    getMyBooks: (params) => apiClient.get('/user/book/my', { params }),
    
    // 下架书籍
    removeBook: (bookId) => apiClient.put(`/user/book/removed/${bookId}`),
    
    // 获取我的收藏
    getFavorites: (params) => apiClient.get('/user/book/favorites', { params }),
    
    // 图书增删改
    create: (data) => http.post('/books', data),
    update: (id, data) => http.put(`/books/${id}`, data),
    delete: (id) => http.delete(`/books/${id}`),
    
    // 图书封面上传
    uploadCover: (file) => http.upload('/books/upload/cover', file),
  },
  
  // 分类相关接口
  category: {
    // 获取所有分类
    getAll: () => http.get('/categories'),
    
    // 获取单个分类详情
    getDetail: (id) => http.get(`/categories/${id}`),
    
    // 创建新分类(管理员)
    create: (data) => http.post('/admin/categories', {
      name: data.name,
      description: data.description
    }),
    
    // 更新分类(管理员)
    update: (id, data) => http.put(`/admin/categories/${id}`, {
      name: data.name,
      description: data.description
    }),
    
    // 删除分类(管理员)
    delete: (id) => http.delete(`/admin/categories/${id}`)
  },
  
  // 交易相关接口
  transaction: {
    // 交易基本操作
    create: (data) => http.post('/transactions', data),
    getDetail: (id) => http.get(`/transactions/${id}`),
    update: (id, data) => http.put(`/transactions/${id}`, data),
    
    // 我的交易记录
    getMySellingTransactions: (params) => http.get('/user/transactions/selling', { params }),
    getMyBuyingTransactions: (params) => http.get('/user/transactions/buying', { params }),
    
    // 交易状态变更
    complete: (id) => http.put(`/transactions/${id}/complete`),
    cancel: (id, reason) => http.put(`/transactions/${id}/cancel`, { reason })
  },
  
  // 收藏相关接口
  favorite: {
    add: (bookId) => http.post(`/favorites`, { bookId }),
    remove: (bookId) => http.delete(`/favorites/${bookId}`),
    getList: (params) => http.get('/user/favorites', { params }),
    check: (bookId) => http.get(`/favorites/check/${bookId}`),
    // 获取用户收藏的书籍列表
    getFavoriteBooks: () => apiClient.get('/user/book/favorites')
  },
  
  // 消息相关接口
  messages: {
    // 获取聊天历史
    getHistory: (userId1, userId2) => {
      // 使用直接的参数格式，而不是嵌套格式
      return apiClient.get(`/messages/history?userId1=${userId1}&userId2=${userId2}`)
    },
    
    // 获取聊天列表
    getChats: () => http.get('/messages/chat/list'),
    
    // 获取未读消息数量
    getUnreadCount: () => http.get('/messages/unread/count'),
    
    // 标记消息为已读
    markAsRead: (messageId) => http.put(`/messages/read/${messageId}`),
    
    // 标记与特定用户的所有聊天消息为已读
    markChatAsRead: (partnerId) => http.put(`/messages/read/chat/${partnerId}`),
    
    // 发送消息
    sendMessage: (receiverId, bookId, content) => http.post('/messages/send', {
      receiverId,
      bookId,
      content
    })
  },
  
  // 评分相关接口
  rating: {
    create: (data) => http.post('/ratings', data),
    getMyRatings: (params) => http.get('/user/ratings', { params }),
    getUserRatings: (userId, params) => http.get(`/users/${userId}/ratings`, { params }),
    getByTransaction: (transactionId) => http.get(`/ratings/transaction/${transactionId}`),
    getAll: () => http.get('/ratings')
  },
  
  // 举报相关接口
  report: {
    create: (data) => http.post('/reports', data),
    getMyReports: () => http.get('/reports'),
    handleReport: (id, data) => {
      // 使用URL查询参数而不是请求体
      const params = new URLSearchParams();
      params.append('status', data.status);      // 必需: processed 或 rejected
      params.append('comment', data.admin_comment);  // 必需: 管理员备注
      
      console.log(`处理举报 ID: ${id}, 参数:`, Object.fromEntries(params));
      return apiClient.put(`/admin/reports/${id}?${params.toString()}`);
    },
  },
  
  // 通知相关接口
  notification: {
    getList: (params) => http.get('/notifications', { params }),
    markAsRead: (id) => http.put(`/notifications/${id}/read`),
    markAllAsRead: () => http.put('/notifications/read/all'),
    getUnreadCount: () => http.get('/notifications/unread/count')
  },
  
  // 管理员接口
  admin: {
    // 用户管理
    getUserList: (params) => {
      // 手动构建URL参数字符串，避免params被嵌套
      const queryParams = new URLSearchParams();
      if (params) {
        Object.keys(params).forEach(key => {
          if (params[key] !== undefined && params[key] !== '') {
            queryParams.append(key, params[key]);
          }
        });
      }
      const queryString = queryParams.toString();
      const url = `/admin/users${queryString ? `?${queryString}` : ''}`;
      
      return apiClient.get(url).then(response => {
        // 添加调试日志
        console.log('用户列表响应处理开始', response);
        
        // 处理响应数据 - 注意：响应拦截器已经提取了.data，所以response就是最终数据
        const data = response; 
        let rowData = [];
        
        // 处理不同的响应结构
        if (data && data.data && Array.isArray(data.data.row)) {
          // 标准格式：{code, message, data: {row, total}}
          rowData = data.data.row;
          console.log('从标准数据结构中提取用户数组:', rowData);
        } else if (data && Array.isArray(data.row)) {
          // 备用格式：{code, message, row, total}
          rowData = data.row;
          console.log('从备用数据结构中提取用户数组:', rowData);
        } else if (data && Array.isArray(data)) {
          // 最简结构：直接是数组
          rowData = data;
          console.log('响应本身就是用户数组:', rowData);
        }
        
        if (rowData.length === 0) {
          console.warn('未从响应中提取到用户数据!', data);
        }
        
        // 转换字段名称
        const formattedUsers = rowData.map(user => ({
          id: user.id,
          username: user.username,
          realName: user.real_name,
          studentId: user.student_id,
          email: user.email,
          phone: user.phone,
          wechat: user.wechat,
          role: user.role,
          status: user.status,
          department: user.department,
          createdAt: user.created_at,
          updatedAt: user.updated_at,
          lastLoginAt: user.last_login_at,
          bio: user.bio,
          stats: {
            bookCount: user.book_count,
            soldCount: user.sold_count,
            boughtCount: user.bought_count,
            favoriteCount: user.favorite_count
          }
        }));
        
        console.log('格式化后的用户数组:', formattedUsers);
        
        // 提取总数
        let total = 0;
        if (data && data.data && typeof data.data.total === 'number') {
          total = data.data.total;
        } else if (data && typeof data.total === 'number') {
          total = data.total;
        } else {
          total = formattedUsers.length;
        }
        
        return {
          users: formattedUsers,
          total: total
        };
      });
    },
    updateUserStatus: (id, status) => {
      // 根据后端API路径，使用status/string/{status}格式
      return http.put(`/admin/users/${id}/status/string/${status}`);
    },
    updateUserRole: (id, role) => {
      // 根据后端API路径，使用role/string/{role}格式
      return http.put(`/admin/users/${id}/role/string/${role}`);
    },
    getUserDetail: (id, params = {}) => {
      // 同样处理getUserDetail
      const queryParams = new URLSearchParams();
      if (params) {
        Object.keys(params).forEach(key => {
          if (params[key] !== undefined && params[key] !== '') {
            queryParams.append(key, params[key]);
          }
        });
      }
      const queryString = queryParams.toString();
      const url = `/admin/users/${id}${queryString ? `?${queryString}` : ''}`;
      
      return http.get(url).then(response => {
        console.log('用户详情响应处理开始:', response);
        
        // 响应拦截器已经提取了.data，所以response就是最终数据
        const data = response;
        
        // 处理不同的响应结构获取用户数据
        let userData = null;
        if (data && data.data && typeof data.data === 'object') {
          // 标准格式：{code, message, data: User}
          userData = data.data;
          console.log('从标准数据结构中提取用户详情:', userData);
        } else if (data && typeof data === 'object' && !Array.isArray(data)) {
          // 简单格式：直接是用户对象
          userData = data;
          console.log('响应本身就是用户详情:', userData);
        }
        
        if (!userData) {
          console.warn('未从响应中提取到用户详情数据!', data);
          return null;
        }
        
        // 转换为驼峰命名格式
        const formattedUser = {
          id: userData.id,
          username: userData.username,
          realName: userData.real_name,
          studentId: userData.student_id,
          email: userData.email,
          phone: userData.phone,
          wechat: userData.wechat,
          role: userData.role,
          status: userData.status,
          department: userData.department,
          createdAt: userData.created_at,
          updatedAt: userData.updated_at,
          lastLoginAt: userData.last_login_at,
          bio: userData.bio,
          stats: {
            bookCount: userData.book_count,
            soldCount: userData.sold_count,
            boughtCount: userData.bought_count,
            favoriteCount: userData.favorite_count
          }
        };
        
        console.log('格式化后的用户详情:', formattedUser);
        return formattedUser;
      });
    },
    resetUserPassword: (id, newPassword) => {
      // 根据后端API路径，使用/users/{id}/{resetPassword}格式
      // 如果没有提供密码，则生成随机密码
      const password = newPassword || Math.random().toString(36).slice(-8);
      return http.post(`/admin/users/${id}/${password}`);
    },
    
    // 添加创建用户和删除用户功能
    createUser: (userData) => {
      // 创建用户API，根据UserValidationUtils中需要的字段
      const createUserData = {
        username: userData.username,
        role: userData.role || 'student',
        // 其他字段可能在后端的DTO中没有直接定义，但是在创建过程中可能会使用
        password: userData.password
      };
      
      console.log('创建用户数据:', createUserData);
      return http.post('/admin/users', createUserData);
    },
    
    deleteUser: (id) => {
      // 删除用户API
      return http.delete(`/admin/users/${id}`);
    },
    
    // 图书管理
    getBookList: (params) => http.get('/admin/books', { params }),
    updateBookStatus: (id, status) => http.put(`/admin/books/${id}/status`, { status }),
    deleteBook: (id) => http.delete(`/admin/book/${id}`),
    
    // 交易管理
    getTransactionList: (params) => http.get('/admin/transactions', { params }),
    
    // 举报管理
    getReportList: (params) => http.get('/admin/reports', { params }).then(response => {
      console.log('获取举报列表响应:', response);
      
      // 处理响应数据
      let reports = [];
      
      // 检查不同的响应结构
      if (response && response.reports && Array.isArray(response.reports)) {
        // 标准格式: {code, message, reports: Array}
        reports = response.reports;
        console.log('从标准数据结构中提取举报列表:', reports);
      } else if (response && Array.isArray(response.data)) {
        // 备用格式: {code, message, data: Array}
        reports = response.data;
        console.log('从data字段中提取举报列表:', reports);
      } else if (response && Array.isArray(response)) {
        // 最简结构: 直接是数组
        reports = response;
        console.log('响应本身就是举报数组:', reports);
      }
      
      if (reports.length === 0) {
        console.warn('未从响应中提取到举报数据!', response);
      }
      
      // 返回格式化后的数据和原始响应
      return {
        reports: reports,
        total: reports.length,
        raw: response
      };
    }),
    getReportDetail: (id) => http.get(`/admin/reports/${id}`).then(response => {
      console.log('获取举报详情响应:', response);
      
      // 处理响应数据
      let reportData = null;
      
      // 检查不同的响应结构
      if (response && response.data && typeof response.data === 'object') {
        // 标准格式: {code, message, data: Object}
        reportData = response.data;
      } else if (response && typeof response === 'object' && !Array.isArray(response)) {
        // 简单格式: 直接是对象
        reportData = response;
      }
      
      if (!reportData) {
        console.warn('未从响应中提取到举报详情数据!', response);
        return null;
      }
      
      return reportData;
    }),
    handleReport: (id, data) => {
      // 使用URL查询参数而不是请求体
      const params = new URLSearchParams();
      params.append('status', data.status);      // 必需: processed 或 rejected
      params.append('comment', data.admin_comment);  // 必需: 管理员备注
      
      console.log(`处理举报 ID: ${id}, 参数:`, Object.fromEntries(params));
      return apiClient.put(`/admin/reports/${id}?${params.toString()}`);
    },
    
    // 数据统计 - 使用正确的路径
    getUserStatistics: () => http.get('/admin/statistics/users'),
    // 兼容旧代码 - getStatistics作为getUserStatistics的别名
    getStatistics: () => http.get('/admin/statistics/users'),
    
    // 系统设置
    getSettings: () => http.get('/admin/settings'),
    updateSettings: (settingsData) => {
      console.log('调用updateSettings API，参数:', { settings: settingsData });
      return http.post('/admin/settings', {
        settings: settingsData
      });
    }
  }
};

export { api };
export default api;



